<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加角色按钮 -->
        <el-row>
          <el-col>
            <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button> 
          </el-col>
        </el-row>

        <!-- 角色列表 -->
        <el-table :data="rolelist" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :class="['bdbottom', i1===0?'bdtop':'','vcenter']" v-for="(item1 ,i1) in scope.row.children" :key="item1.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag @close="removeRightById(scope.row,item1.id)"
                            :closable="true"
                            >{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级三级权限 -->
                        <el-col :span="19">
                            <el-row :class="[i2 === 0 ?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                                <!-- 二级 -->
                              <el-col :span="6">
                                <el-tag type="success" :closable="true"
                                @close="removeRightById(scope.row,item2.id)"
                                >{{item2.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                              </el-col>
                              <!-- 三级 -->
                              <el-col :span="18">
                                <el-tag :closable="true" type="warning"
                                 v-for="(item3,i3) in item2.children"
                                :key="item3.id"
                                @close="removeRightById(scope.row,item3.id)"
                                >
                                {{item3.authName}}
                                </el-tag>   
                              </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称"  prop="roleName"></el-table-column>
            <el-table-column label="角色描述"  prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
                <template slot-scope="scope">
                    <el-button @click="showEditDialog(scope.row.id)" type="primary"
                       icon="el-icon-edit" size="mini">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeRoleById(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting"
                       @click="showSetRightDialog(scope.row)" size="mini">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table> 
    </el-card>
    
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" width="50%" :visible.sync="addRoleDialogVisible"
    @close="roleDialogClosed" >
        <!-- 内容主体区 -->
        <el-form :model="roleForm" :rules="addFormRules"
        ref="roleFormRef" label-width="70px">
            <el-form-item label-width="100px" label="角色名称" prop="roleName">
                <el-input v-model="roleForm.roleName"></el-input>
            </el-form-item>             
            <el-form-item label-width="100px" label="角色描述" prop="roleDesc">
                <el-input v-model="roleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="addRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRolesList">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 编辑角色的对话框 -->
     <el-dialog title="修改用户" :visible.sync="editDialogVisible"
     width="50%"  @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" 
        ref="editFormRef" label-width="70px">            
            <el-form-item label-width="100px" label="角色名称" prop="roleName">
                <el-input v-model="editForm.roleName"></el-input>
            </el-form-item>             
            <el-form-item label-width="100px" label="角色描述" prop="roleDesc">
                <el-input v-model="editForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoleInfo">确 定</el-button>
        </span>
     </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" 
    @close="setRightDialogClosed">
        <!-- 树形控件 -->
        <el-tree 
        :data="rightslist" :props="treeProps" 
        show-checkbox node-key="id" default-expand-all 
        :default-checked-keys="defKeys" ref="treeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
    data() {
        return {
            // 所有角色列表数据
            rolelist: [],
            // 控制添加角色对话框的显示隐藏
            addRoleDialogVisible: false,
            // 用户信息对象
            roleForm: {
                roleName: '',
                roleDesc:''
            },
            // 添加表单的验证规则对象   :rules="addFormRules"
            addFormRules: {
                // username 表单验证规则  prop="username"
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    }
                ]
            },
            // 查询到的角色信息对象
            editForm: {},
            // 控制编辑角色的对话框的显示与隐藏
            editDialogVisible: false,
            // 查询到的用户信息对象的验证规则对象
            editFormRules: {
                roleName: [
                    {
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [
                    {
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    }
                ]
            },
            // 控制分配权限对话框的显示与隐藏
            setRightDialogVisible: false,
            // 所有的权限数据
            rightslist: [],
            // 树形控件的属性绑定对象
            treeProps: {
                // 作为树的分隔（父子嵌套） children 
                children: 'children',
                // 树名文本 authName
                label: 'authName'
            },
            // 默认选中的树节点id值
            defKeys: [],
            // 当前即将分配权限的角色ID
            roleId:''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        // 获取所有角色列表数据
        async getRolesList() {
            const { data: res } = await this.$http.get('roles')
            // console.log(res);
            if (res.meta.status !== 200) {
                return this.$message.error('获取失败')
            }
            this.rolelist = res.data
        },
        // 点击按钮 添加角色的函数
        async addRolesList() {
            this.$refs.roleFormRef.validate(async valid => {
                // console.log(valid);  ture  or  false
                if (!valid) return
                const { data: res } = await this.$http.post('roles', this.roleForm)
                if (res.meta.status !== 201) {
                    return this.$message.error('添加失败')
                }
                this.getRolesList()
                this.$message.success('添加成功')
                this.addRoleDialogVisible = false
            })
        },
        // 监听添加角色对话框的关闭事件
        roleDialogClosed() {
            // 重置表单
            this.$refs.roleFormRef.resetFields()
        },
        // 展示编辑用户的对话框
        async showEditDialog(id) {
            const { data: res } = await this.$http.get(`roles/${id}`)
            if (res.meta.status !== 200) {
                return this.$message.error('查询用户信息失败')
            }
            // console.log('查询用户信息',res);
            this.editForm = res.data
            this.editDialogVisible = true
        },
        // 编辑用户信息并提交
        editRoleInfo() { 
            this.$refs.editFormRef.validate(async valid => {
            if (!valid) return 
            //   发请求
              const { data: res } = await this.$http.put(`roles/${this.editForm.roleId}`,
                  {
                      roleName: this.editForm.roleName,
                      roleDesc: this.editForm.roleDesc
                  })
                //   console.log(res);
              if (res.meta.status !== 200) {
                this.$message.error('修改失败')
              }
            this.$message.success('修改成功') 
            this.getRolesList()
            this.editDialogVisible = false
        })
        },
        // 监听编辑角色对话框的关闭事件
        editDialogClosed() {
            // 重置表单
            this.$refs.editFormRef.resetFields()
        },
        // 删除角色
        removeRoleById(id) {
                // 弹窗提示 询问是否删除
            this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async() => {
                const { data: res } = await this.$http.delete(`roles/${id}`)
                if (res.meta.status !== 200) {
                    this.$message.error('删除失败')
                }
                this.getRolesList()
                this.$message({
                type: 'success',
                message: '删除成功!'
            });
            }).catch((e) => {
                // console.log(e);
            this.$message({
                type: 'info',
                message: '已取消删除'
            });          
            });
        },
        // 根据ID删除对应权限
        removeRightById(role,rightId) {
          // 弹框提示用户是否删除
          this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          }).then(async() => {
          const { data:res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
              if (res.meta.status !== 200) {
                this.$message({
                type: 'info',
                message: '删除失败'
              }); 
              }
            //  返回的data, 是当前角色下最新的权限数据
            // this.getRolesList() 调用这个函数 页面会重新完整渲染
            role.children = res.data
            this.$message({
                type: 'success',
                message: '删除成功!'
            });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        },
        // 展示分配权限的对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            // 获取所有权限的数据
            const { data:res } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) {
                this.$message.error('获取数据失败')
            }
            // 把获取的权限数据保存到 data 中
            this.rightslist = res.data
            // console.log(this.rightslist);

            // 递归获取三级节点的ID
            this.getLeafKeys(role,this.defKeys)
            this.setRightDialogVisible = true
        },
        // 通过递归的形式，获取角色下所有三级权限的id,并保存到数组defKeys
        getLeafKeys(node, arr) {
            // 如果当前节点不包含children就是三级节点
            if (!node.children) {
               return  arr.push(node.id)
            }
            // 不是三级节点  使用递归
            node.children.forEach(item => {
                this.getLeafKeys(item,arr)
            })
        },
        // 监听分配权限的对话框的关闭事件
        setRightDialogClosed() {
            this.defKeys = []
        },
        // 点击为角色分配权限
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys(),
            ]
            // console.log(keys);
            const idStr = keys.join(',')
            const { data:res } = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
            // console.log(res);
            if (res.meta.status !== 200) {
                this.$message.error('分配权限失败')
            }
            this.$message.success('分配成功')
            this.getRolesList()
            this.setRightDialogVisible = false
        }
        
    }
}
</script>

<style lang="less" scoped>
.el-tag{
    margin: 7px;
}
.bdtop{
    border-top: 1px solid #eee;
}

.bdbottom{
    border-bottom: 1px solid #eee;
}

.vcenter{
    display: flex;
    align-items: center;
}
</style>